package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.*;
import com.erp.gather.domain.bo.ErpSellerProductBo;
import com.erp.gather.domain.vo.ErpProductBrandVo;
import com.erp.gather.domain.vo.ErpSellerProductExpandVo;
import com.erp.gather.domain.vo.ErpSellerProductSkuVo;
import com.erp.gather.domain.vo.ErpSellerProductVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IErpProductBrandService;
import com.erp.gather.service.IErpSellerProductService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gather.api.domain.ErpSellerProduct;
import com.ruoyi.gather.api.domain.ErpSellerProductExpand;
import com.ruoyi.gather.api.domain.ErpSellerProductSku;
import com.ruoyi.gather.api.domain.ErpSellerStoreProductExpand;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * ERP个人商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）Service业务层处理
 *
 * @author erp
 * @date 2023-03-28
 */
@RequiredArgsConstructor
@Service
public class ErpSellerProductServiceImpl implements IErpSellerProductService {

    private final ErpSellerProductMapper baseMapper;
    private final ErpSellerProductSkuMapper erpSellerProductSkuMapper;
    private final ErpSellerProductExpandMapper erpSellerProductExpandMapper;
    //	private final IErpSellerStoreProductService iErpSellerStoreProductService;
    private final ErpSellerStorePromiseTemplateMapper erpSellerStorePromiseTemplateMapper;
    private final IErpProductBrandService iErpProductBrandService;
    private final ErpCollectProductCategoryMapper erpCollectProductCategoryMapper;

    /**
     * 查询ERP个人商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public ErpSellerProductVo queryById(Long id) {

        ErpSellerProductVo productVo = baseMapper.selectVoById(id);

        // 获取sku
        List<ErpSellerProductSkuVo> productVoSkus = erpSellerProductSkuMapper.selectVoList(
                new LambdaQueryWrapper<ErpSellerProductSku>().eq(ErpSellerProductSku::getSellerProductId, id));
        productVo.setSkuList(productVoSkus);

        // 获取产品扩展表
        ErpSellerProductExpandVo productExpandVo = erpSellerProductExpandMapper.selectVoOne(
                new LambdaQueryWrapper<ErpSellerProductExpand>().eq(ErpSellerProductExpand::getSellerProductId, id));
        productVo.setExpand(productExpandVo);

        // 商品类目转义拼接--小程序回显用
        String categoryName = "";
        if (productVo.getCategoryId() != null) {
            // 查询商品类目名称
            ErpCollectProductCategory category = erpCollectProductCategoryMapper.selectById(productVo.getCategoryId());
            if (category != null && StringUtils.isNotEmpty(category.getAncestors())) {
                List<String> list = Arrays.asList(category.getAncestors().split(","));
                for (String str : list) {
                    ErpCollectProductCategory entity = erpCollectProductCategoryMapper.selectById(str);
                    if (entity != null) {
                        categoryName = categoryName + entity.getName() + "/";
                    }
                }
            }
            categoryName = categoryName + category.getName();
        }
        productVo.setCategoryName(categoryName);
        // 品牌名称翻译--小程序回显用
        if (productVo.getExpand() != null && productVo.getExpand().getBrandId() != null) {
            ErpProductBrandVo brandVo = iErpProductBrandService.queryById(productVo.getExpand().getBrandId());
            if (brandVo != null) {
                productVo.setBrandName(brandVo.getBrandName());
            }
        }
        return productVo;
    }

    /**
     * 查询ERP个人商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public TableDataInfo<ErpSellerProductVo> queryPageList(ErpSellerProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerProduct> lqw = buildQueryWrapper(bo);

        List<SFunction<ErpSellerProduct, ?>> columns = new ArrayList<>();
        columns.add(ErpSellerProduct::getId);
        columns.add(ErpSellerProduct::getCategoryId);
        columns.add(ErpSellerProduct::getSubject);
        columns.add(ErpSellerProduct::getImageURLs);
        columns.add(ErpSellerProduct::getProductPrice);
        lqw.select(columns);


        Page<ErpSellerProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        result.getRecords().forEach(vo -> {
            // 获取id
            Long id = vo.getId();
            LambdaQueryWrapper<ErpSellerProductExpand> expandlqw = new LambdaQueryWrapper<ErpSellerProductExpand>();
            expandlqw.select(ErpSellerProductExpand::getId, ErpSellerProductExpand::getTemplateId,
                    ErpSellerProductExpand::getBrandId);
            expandlqw.eq(ErpSellerProductExpand::getSellerProductId, id);
            ErpSellerProductExpandVo productExpandVo = erpSellerProductExpandMapper.selectVoOne(expandlqw);

            // 获取运费模板
            vo.setTemplateId(productExpandVo.getTemplateId());

            // 获取品牌名称
            Long brandId = productExpandVo.getBrandId();
            if (brandId != null) {
                ErpProductBrandVo brandVo = iErpProductBrandService.queryById(brandId);
                vo.setBrandName(brandVo.getBrandName());
            }

        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询ERP个人商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public List<ErpSellerProductVo> queryList(ErpSellerProductBo bo) {
        LambdaQueryWrapper<ErpSellerProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerProduct> buildQueryWrapper(ErpSellerProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerProduct> lqw = Wrappers.lambdaQuery();
        if (bo.getSellerId() != null) {
            lqw.eq(bo.getSellerId() != null, ErpSellerProduct::getSellerId, bo.getSellerId());
        } else {
            lqw.eq(ErpSellerProduct::getSellerId, SecurityUtils.getUserId());
        }
        lqw.eq(bo.getCollectProductId() != null, ErpSellerProduct::getCollectProductId, bo.getCollectProductId());
//		lqw.eq(bo.getCategoryId() != null, ErpSellerProduct::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getImageURLs()), ErpSellerProduct::getImageURLs, bo.getImageURLs());
        lqw.eq(StringUtils.isNotBlank(bo.getSubject()), ErpSellerProduct::getSubject, bo.getSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getWhite()), ErpSellerProduct::getWhite, bo.getWhite());
        lqw.eq(StringUtils.isNotBlank(bo.getMarketing()), ErpSellerProduct::getMarketing, bo.getMarketing());
        lqw.eq(StringUtils.isNotBlank(bo.getMedia()), ErpSellerProduct::getMedia, bo.getMedia());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectProductPrice()), ErpSellerProduct::getCollectProductPrice,
                bo.getCollectProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPrice()), ErpSellerProduct::getProductPrice, bo.getProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileDetail()), ErpSellerProduct::getMobileDetail, bo.getMobileDetail());
        lqw.eq(bo.getPackageLength() != null, ErpSellerProduct::getPackageLength, bo.getPackageLength());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageWidth()), ErpSellerProduct::getPackageWidth, bo.getPackageWidth());
        lqw.eq(bo.getPackageHeight() != null, ErpSellerProduct::getPackageHeight, bo.getPackageHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getGrossWeight()), ErpSellerProduct::getGrossWeight, bo.getGrossWeight());
        lqw.eq(bo.getProductUnit() != null, ErpSellerProduct::getProductUnit, bo.getProductUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomAttributes()), ErpSellerProduct::getCustomAttributes,
                bo.getCustomAttributes());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), ErpSellerProduct::getDetail, bo.getDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getDetailImg()), ErpSellerProduct::getDetailImg, bo.getDetailImg());
        lqw.eq(bo.getSizechartId() != null, ErpSellerProduct::getSizechartId, bo.getSizechartId());
        lqw.eq(StringUtils.isNotBlank(bo.getModeSizeChartList()), ErpSellerProduct::getModeSizeChartList,
                bo.getModeSizeChartList());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpSellerProduct::getCollectUrl, bo.getCollectUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerProduct::getRevision, bo.getRevision());

        //确认用户
        // 商品类目
        lqw.apply(bo.getCategoryId() != null,
                " category_id in (SELECT id FROM `erp_collect_product_category` WHERE id = " + bo.getCategoryId()
                        + " OR FIND_IN_SET( " + bo.getCategoryId() + " , ancestors ))");

        String skuCode = bo.getSkuCode();
        if (StringUtils.isNotEmpty(skuCode)) {
            lqw.apply("id in (select `seller_product_id` from `erp_seller_product_sku`  where `sku_code` = '" + skuCode
                    + "')");
        }

        // 是否上架
        String onShelf = bo.getOnShelf();
        if (StringUtils.isNotEmpty(onShelf)) {
            if ("0".equals(onShelf)) {
                lqw.apply(
                        "collect_product_id in (select collect_product_id from erp_seller_store_product sp left join erp_seller_store_product_expand spe on sp.id = spe.`seller_store_product_id` where sp.store_id = "
                                + bo.getStoreId() + " and spe.`status` != 3)");
            } else {
                lqw.apply(
                        "collect_product_id not in (select collect_product_id from erp_seller_store_product sp left join erp_seller_store_product_expand spe on sp.id = spe.`seller_store_product_id` where sp.store_id = "
                                + bo.getStoreId() + " and (spe.status != 3 or spe.`product_status_type` = -3))");
            }
        }

        String expandSql = "";

        String classifyLabel = bo.getClassifyLabel();
        if (StringUtils.isNotEmpty(classifyLabel)) {
            expandSql += " and classify_label like '%" + classifyLabel + "%' ";
        }
        // 商品属性
        if (bo.getIsGeneral() != null) {
            if (bo.getIsGeneral().equals(0)) { // 普货
//				lqw.apply(
//						"id in (select `seller_product_id` from `erp_seller_product_expand`  where `product_attribute` =0)");
                expandSql += " and product_attribute =0 ";
            } else if (bo.getIsGeneral().equals(1)) { // 特货
//				lqw.apply(
//						"id in (select `seller_product_id` from `erp_seller_product_expand`  where `product_attribute` in (1,2,3))");
                expandSql += " and product_attribute in (1,2,3) ";
            }
        }
        // 品牌id
        String brandId = bo.getBrandId();
        if (brandId != null) {
//			lqw.apply(" id in (SELECT seller_product_id FROM erp_seller_product_expand WHERE brand_id in( " + brandId
//					+ "))");
            expandSql += " and brand_id in (" + brandId + ") ";
        }
        // 运费模板id
        Integer templateId = bo.getTemplateId();
        if (templateId != null) {
//			lqw.apply(" id in (SELECT seller_product_id FROM erp_seller_product_expand WHERE template_id = "
//					+ templateId + ")");
            expandSql += " and template_id = " + templateId + " ";
        }
        // 添加expandSql
        if (StringUtils.isNotEmpty(expandSql)) {
            expandSql = expandSql.substring(4);
            lqw.apply(" id in (SELECT seller_product_id FROM erp_seller_product_expand WHERE " + expandSql + ")");
        }

        lqw.orderByDesc(ErpSellerProduct::getUpdateTime);
        return lqw;
    }

    /**
     * 新增ERP个人商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean insertByBo(ErpSellerProductBo bo) {
        ErpSellerProduct add = BeanUtil.toBean(bo, ErpSellerProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改ERP个人商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean updateByBo(ErpSellerProductBo bo) {
        ErpSellerProduct update = BeanUtil.toBean(bo, ErpSellerProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerProduct entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除ERP个人商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        int deleteBatchIds = baseMapper.deleteBatchIds(ids);
        if (deleteBatchIds > 0) {

//			// 删除sku
//			erpSellerProductSkuMapper.delete(
//					new LambdaQueryWrapper<ErpSellerProductSku>().in(ErpSellerProductSku::getSellerProductId, ids));
//			// 删除扩展类
//			erpSellerProductExpandMapper.delete(new LambdaQueryWrapper<ErpSellerProductExpand>()
//					.in(ErpSellerProductExpand::getSellerProductId, ids));
            return true;
        }
        return false;
    }

    @Override
    public void autoPush(List<Long> storeIds) {

        for (Long storeId : storeIds) {
            // 根据店铺获取个人产品库中未上传的商品
            LambdaQueryWrapper<ErpSellerProduct> lqw = new LambdaQueryWrapper<ErpSellerProduct>();
//			lqw.apply("`id` NOT IN (SELECT seller_product_id FROM `erp_seller_store_product` WHERE store_id = "
//					+ storeId + ")");
            lqw.apply("`id` NOT IN (SELECT seller_product_id FROM `erp_seller_store_product`)");
            lqw.orderByAsc(ErpSellerProduct::getId);
            lqw.last("limit 1");
            List<ErpSellerProduct> unPushList = baseMapper.selectList(lqw);
            if (unPushList != null && unPushList.size() != 0) {
                // 获取一个
                ErpSellerProduct erpSellerProduct = unPushList.get(0);

                // 创建发布扩展类，绑定运费模板、服务模板
                ErpSellerStoreProductExpand expand = new ErpSellerStoreProductExpand();

//				// 根据店铺id和固定模板名字获取运费模板id
//				LambdaQueryWrapper<ErpSellerStoreFreightTemplate> freLqw = new LambdaQueryWrapper<ErpSellerStoreFreightTemplate>();
//				freLqw.eq(ErpSellerStoreFreightTemplate::getSellerStoreId, storeId);
//				freLqw.eq(ErpSellerStoreFreightTemplate::getTemplateName, "自动发布商品运费通用模板");
//				freLqw.last("limit 1");
//				ErpSellerStoreFreightTemplate freightTemplate = erpSellerStoreFreightTemplateMapper.selectOne(freLqw);
//				if (freightTemplate == null)
//					continue; // 没有模板发布失败
//				expand.setFreightTemplateId(freightTemplate.getTemplateId()); // 运费模板
                // 获取服务模板
                LambdaQueryWrapper<ErpSellerStorePromiseTemplate> proLqw = new LambdaQueryWrapper<ErpSellerStorePromiseTemplate>();
                proLqw.eq(ErpSellerStorePromiseTemplate::getSellerStoreId, storeId);
                proLqw.last("limit 1");
                ErpSellerStorePromiseTemplate promiseTemplate = erpSellerStorePromiseTemplateMapper.selectOne(proLqw);
                if (promiseTemplate == null)
                    continue; // 没有模板发布失败
                expand.setPromiseTemplateId(promiseTemplate.getTemplateId()); // 服务模板

                // 设置调价规则
                expand.setPriceAdjustmentMethod("0"); // 手动设置模式
                expand.setReadjustPricesType(1); // 加上
                expand.setReadjustPrices(new BigDecimal(20)); // 上浮20%
                expand.setReduceStrategy("payment_success_deduct"); // 支付减库存

//				iErpSellerStoreProductService.push(erpSellerProduct.getId(), storeId, 999l, expand);
            }
        }

    }

    /**
     * 查询个人产品库中可以上传的2.0商品
     *
     * @return
     */
    @Override
    public List<ErpSellerProduct> getErpSellerProduct20() {
        return baseMapper.getErpSellerProduct20();
    }

    @Override
    public R<Object> getSellerProductInfo(ErpSellerProduct bo) {
        LambdaQueryWrapper<ErpSellerProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSellerId() != null, ErpSellerProduct::getSellerId, bo.getSellerId());
        lqw.eq(bo.getCollectProductId() != null, ErpSellerProduct::getCollectProductId, bo.getCollectProductId());
//		lqw.eq(bo.getCategoryId() != null, ErpSellerProduct::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getImageURLs()), ErpSellerProduct::getImageURLs, bo.getImageURLs());
        lqw.eq(StringUtils.isNotBlank(bo.getSubject()), ErpSellerProduct::getSubject, bo.getSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getWhite()), ErpSellerProduct::getWhite, bo.getWhite());
        lqw.eq(StringUtils.isNotBlank(bo.getMarketing()), ErpSellerProduct::getMarketing, bo.getMarketing());
        lqw.eq(StringUtils.isNotBlank(bo.getMedia()), ErpSellerProduct::getMedia, bo.getMedia());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectProductPrice()), ErpSellerProduct::getCollectProductPrice,
                bo.getCollectProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPrice()), ErpSellerProduct::getProductPrice, bo.getProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileDetail()), ErpSellerProduct::getMobileDetail, bo.getMobileDetail());
        lqw.eq(bo.getPackageLength() != null, ErpSellerProduct::getPackageLength, bo.getPackageLength());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageWidth()), ErpSellerProduct::getPackageWidth, bo.getPackageWidth());
        lqw.eq(bo.getPackageHeight() != null, ErpSellerProduct::getPackageHeight, bo.getPackageHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getGrossWeight()), ErpSellerProduct::getGrossWeight, bo.getGrossWeight());
        lqw.eq(bo.getProductUnit() != null, ErpSellerProduct::getProductUnit, bo.getProductUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomAttributes()), ErpSellerProduct::getCustomAttributes,
                bo.getCustomAttributes());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), ErpSellerProduct::getDetail, bo.getDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getDetailImg()), ErpSellerProduct::getDetailImg, bo.getDetailImg());
        lqw.eq(bo.getSizechartId() != null, ErpSellerProduct::getSizechartId, bo.getSizechartId());
        lqw.eq(StringUtils.isNotBlank(bo.getModeSizeChartList()), ErpSellerProduct::getModeSizeChartList,
                bo.getModeSizeChartList());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpSellerProduct::getCollectUrl, bo.getCollectUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerProduct::getRevision, bo.getRevision());

        ErpSellerProduct erpSellerProduct = baseMapper.selectOne(lqw);
        if (Objects.isNull(erpSellerProduct)) {
            return R.fail("未查找到信息");
        } else {
            return R.ok(erpSellerProduct);
        }
    }


}
